require 'digest/sha1'

class User < ActiveRecord::Base
	validates_presence_of :username, :pass_hash, :house_id
	validates_uniqueness_of :username
	
	belongs_to :house
	has_many :checks
	
  def self.authenticate(username, password)
    user = self.find_by_username(username)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.pass_hash != expected_password
        user = nil
      end
    end
    user
  end
  
   
  def password
    @password
  end
  
  def password=(pwd)
    @password = pwd
    create_new_salt
    self.pass_hash = User.encrypted_password(self.password, self.salt)
  end
	
	private
	
	def self.encrypted_password(password,salt)
	  Digest::SHA1.hexdigest(password+salt)
	end
	
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end
